import { corsHeaders } from '../utils/cors'
import { PasswordModel } from '../models/password'
import { Logger } from '../utils/logger'
import { generateRandomKey, encrypt, decrypt } from '../utils/crypto'
import { kvHelper } from '../utils/kv-helper'
import { authenticate } from '../utils/crypto.js'

export const passwordHandler = {
  async list(request, env) {
    try {
      const { userId } = request.user;
      const logger = new Logger(env).setModule('Password:list');
      logger.info(`用户 ${userId} 获取密码列表`);
      
      const passwords = await PasswordModel.findByUser(env, userId);
      logger.info(`获取密码列表成功`, { passwords });

      return new Response(JSON.stringify({
        ok: true,
        data: passwords
      }), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      console.error('获取密码列表失败:', error);
      return new Response(JSON.stringify({ 
        ok: false,
        error: '获取密码列表失败' 
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  async create(request, env) {
    const logger = new Logger(env).setModule('Password:create');
    try {
      const { userId, email } = request.user;
      const { url, username, note, password } = await request.json();

      // 验证必填字段
      if (!username || !password) {
        return new Response(JSON.stringify({
          ok: false,
          error: '缺少必填字段'
        }), {
          status: 400,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }     
      
      // 用加密密钥对密码加密
      const masterKey = await kvHelper.getMasterKey(env, email);
      if(!masterKey){
        return new Response(JSON.stringify({
          ok: false,
          error: '密钥超时',
          code: 'KEY_TIMEOUT'
        }), {
          status: 400,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }
      const { encrypted, iv } = await encrypt(password, masterKey);

      // 创建密码记录
      const result = await PasswordModel.create(env, {
        userId,        
        url,
        username,
        encryptedPassword: encrypted,
        passwordIv: iv,
        note: note || ''
      });
      

      return new Response(JSON.stringify({
        ok: true,
        message: '密码创建成功',
        data: {
          id: result.id,          
          url,
          username,
          note: note || '',
          createdAt: new Date().toISOString()
        }
      }), {
        status: 201,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      logger.error('创建密码失败', error);
      return new Response(JSON.stringify({ 
        ok: false,
        error: '创建密码失败',
        message: env.DEBUG === 'true' ? error.message : undefined
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  async update(request, env) {
    try {
      const { userId, email } = request.user;
      const { id } = request.params;
      const { url, username, password, note } = await request.json();
      
      const masterKey = await kvHelper.getMasterKey(env, email);
      const { encrypted, iv } = await encrypt(password, masterKey);
      
      const result = await PasswordModel.update(env, id, {        
        url,
        username,
        encryptedPassword: encrypted,
        passwordIv: iv,
        note
      });
      
      return new Response(JSON.stringify({
        ok: true,
        message: '更新成功'
      }), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      return new Response(JSON.stringify({
        ok: false,
        error: '更新密码失败'
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  async delete(request, env) {
    try {
      const { id } = request.params;
      await PasswordModel.delete(env, id);
      
      return new Response(JSON.stringify({
        ok: true,
        message: '删除成功'
      }), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      return new Response(JSON.stringify({
        ok: false,
        error: '删除密码失败'
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  async getDetail(request, env) {
    const logger = new Logger(env).setModule('Password:getDetail');
    try {
      const { id } = request.params;
      const { email } = request.user;

      // 获取密码记录
      const password = await PasswordModel.findById(env, id);
      if (!password) {
        return new Response(JSON.stringify({
          ok: false,
          error: '密码不存在'
        }), {
          status: 404,
          headers: { ...corsHeaders, 'Content-Type': 'application/json' }
        });
      }
      logger.debug('获取密码详情', { id , email});
      // 获取主密钥
      const masterKey = await kvHelper.getMasterKey(env, email);
      
      // 解密密码
      const decryptedPassword = await decrypt(
        password.encrypted_password,
        password.password_iv,
        masterKey
      );
      password.password = decryptedPassword;
      logger.debug('获取密码详情成功', { id , email,decryptedPassword});
      return new Response(JSON.stringify({
        ok: true,
        data: {
          ...password
        }
      }), {
        status: 200,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    } catch (error) {
      console.error('获取密码详情失败:', error);
      return new Response(JSON.stringify({
        ok: false,
        error: '获取密码详情失败'
      }), {
        status: 500,
        headers: { ...corsHeaders, 'Content-Type': 'application/json' }
      });
    }
  },

  // 获取密码数量
  async handleGetPasswordCount(request, env) {
    // 验证身份
    const { userId } = request.user;

    try {
        const count = await PasswordModel.getCountByUser(env, userId);
        
        return new Response(JSON.stringify({
            ok: true,
            data: { count }
        }), {
            headers: { ...corsHeaders, 'Content-Type': 'application/json' }  // 添加 CORS 头
        });
    } catch (error) {
        console.error('获取密码数量失败:', error);
        return new Response(JSON.stringify({
            ok: false,
            error: '获取密码数量失败'
        }), {
            status: 500,
            headers: { ...corsHeaders, 'Content-Type': 'application/json' }  // 添加 CORS 头
        });
    }
  }
} 